<!--
 * @Author: poro poroone@163.com
 * @Date: 2023-04-20 11:30:07
 * @LastEditors: poro poroone@163.com
 * @LastEditTime: 2023-04-20 16:59:21
 * @FilePath: \Vue学习\vue3\src\view\2.ref.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <div>
        <div>
            Ref:{{ man }}
        </div>
        <hr>
        <div>
            shallowRef:{{ man3 }}
        </div>
        <hr>
        <div>customRef:{{ obj }}</div>
        <hr>
        <div ref="dom">我是dom</div>
    </div>
    <button @click="change">修改</button>
</template>
    
<script setup lang='ts'>
import type { Ref } from "vue"
import { ref, isRef, shallowRef, triggerRef, customRef } from 'vue'
const dom = ref<HTMLDivElement>() 

function myRef<T>(value: T) {
    // 防抖
    let time: any
    return customRef((track, trigger) => {
        return {
            // 收集依赖
            get() {
                track()
                return value
            },
            // 触发依赖
            set(newVal) {
                clearTimeout(time)
                time = setTimeout(() => {
                    console.log("我触发了")
                    value = newVal
                    time = null
                    trigger()
                }, 500)
            }
        }
    })
}

const obj = myRef<string>("customRef:[poro]")


// ref        shallowRef
// ref        深层响应式  全部都有
//shallowRef  浅层响应式 只到.value
type M = {
    name: string
}
// ref
const man: Ref<M> = ref<M>({ name: "魄罗" })
// 非ref
const man2 = { name: "魄罗" }
// shallowRef
const man3 = shallowRef({ name: "魄罗shallow" })

const change = () => {
    //1. ref
    // man.value.name = "小魄罗"
    // console.log(man)
    // 2.isRef
    // console.log(isRef(man))
    // console.log(isRef(man2))

    // 3.shallowRef 只能响应浅层的 不能和ref一起使用否则会影响 shallowRef 造成试图的更新
    // man3.value.name = "大魄罗"
    // console.log(man3)

    // shallowRef神响应
    // man3.value = {
    //     name: "超大魄罗"
    // }
    // 强制更新收集的依赖
    // 4.triggerRef(man3)
    // triggerRef(man3)
    // console.log(man3)
    // triggerRef
    // 在ref更新的时候会调用底层triggerRef
    // 5.customRef
    obj.value = "customRef{修改了poro}"
    console.log(obj)
    // 6.ref也可以读取dom属性
    console.log(dom.value?.innerText)
}
</script>
<style scoped></style>